<template>
  <nut-config-provider :theme="theme" :theme-vars="themeVars">
    <view :style="{backgroundColor: themeVars.pageBackgroundColor,padding: themeVars.pagePadding,height:'100vh'}">
      <!--顶部-->
      <nut-searchbar v-model="queryParam.searchKey">
        <template #leftout>
          <view style="display: flex;align-items: center" @click="visible=true">
            <view class="city-box">{{ queryParam.adcodeName }}</view>
            <IconFont name="rect-right" size="14"></IconFont>
          </view>
        </template>
        <template #leftin>
          <Search2/>
        </template>
        <template #rightout><span @click="search">搜索</span></template>

      </nut-searchbar>
      <!--tab-->
      <nut-tabs v-model="queryParam.type" :ellipsis="false" :title-gutter="10" auto-height @change="changeTabs">
        <nut-tab-pane title="需求广场" pane-key="DEMAND"
                      :style="{padding: '10px' ,background: themeVars.pageBackgroundColor } ">

          <Opportunity v-if="demandData.length > 0 "
                       @click="Taro.navigateTo({url:'/pages/view/publishInfo/index?id='+item.id})" :data="item"
                       v-for="item in demandData"/>
          <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>
        </nut-tab-pane>

        <nut-tab-pane title="闲置物品" pane-key="IDLE"
                      :style="{padding: '10px' ,background: themeVars.pageBackgroundColor } ">
          <Opportunity v-if="idleData.length > 0 "
                       @click="Taro.navigateTo({url:'/pages/view/publishInfo/index?id='+item.id})" :data="item"
                       v-for="item in idleData"/>
          <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>
        </nut-tab-pane>

        <nut-tab-pane title="库存处理" pane-key="STOCK"
                      :style="{padding: '10px' ,background: themeVars.pageBackgroundColor } ">
          <SpecCommodity class="card"  v-if="stockData.length > 0 " :data="item" v-for="item in stockData"
                         @click="Taro.navigateTo({url:'/pages/view/commodityInfo/index?id='+item.id})"
           style="margin-bottom: 5px;width: 640rpx"
          />
          <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>

        </nut-tab-pane>

        <nut-tab-pane title="特价商品" pane-key="SPE_PRICE"
                      :style="{padding: '10px' ,background: themeVars.pageBackgroundColor } ">
          <SpecCommodity class="card"   v-if="spePriceData.length > 0 " :data="item" v-for="item in spePriceData"
                         @click="Taro.navigateTo({url:'/pages/view/commodityInfo/index?id='+item.id})"
                         style="margin-bottom: 5px;width: 640rpx"
          />
          <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>
        </nut-tab-pane>

      </nut-tabs>
      <view class="fixed-bottom">
        <nut-button v-if="queryParam.type=='DEMAND'" type="primary" style="width: 200px"
                    @click="Taro.navigateTo({url:'/pages/view/publishForm/index'})">发布需求
        </nut-button>
        <nut-button v-if="queryParam.type=='IDLE'" color="#0051DC" style="width: 200px"
                    @click="Taro.navigateTo({url:'/pages/view/publishForm/index'})">
          发布闲置
        </nut-button>

      </view>

    </view>
    <nut-cascader
        v-model:visible="visible"
        v-model="queryParam.adcode"
        title="选择地址"
        :options="areaData"
        @change="change"

    ></nut-cascader>
  </nut-config-provider>
</template>

<script>

import {ref} from 'vue';
import useTheme from "../../../hooks/useTheme";
import Taro from "@tarojs/taro";
import {IconFont} from "@nutui/icons-vue";
import {amapCGeocodeRegeo} from "../../../api/dev";
import {parseAddressCode} from "../../../utils/strUtils";
import {twPublishPageApi} from "../../../api/publish";
import {twProductPageApi} from "../../../api/product";
import {emptyUrl} from "../../../utils/imgUtils";

const {theme, themeVars} = useTheme()
const areaData = JSON.parse(Taro.getStorageSync("areaJson"));

const visible = ref(false)


const change = (val, arr) => {
  console.log('change', val, arr)
  queryParam.value.adcode = val;
  queryParam.value.adcodeName = arr[2].text;
  queryParam.value.addrAdcode = val[2]
  refresh()

}


const queryParam = ref({
  searchKey: "",
  type: 'DEMAND',
  current: 1,
  size: 10,
  pages: 0,
  addrAdcode: ''
})

const getLocation = () => {
  Taro.getLocation({
    type: 'gcj02',
    altitude: true,
    isHighAccuracy: true,
    success: function (res) {
      const {
        address,
        errMsg,
        latitude,
        longitude,
        name
      } = res
      amapCGeocodeRegeo(`${longitude},${latitude}`).then(res => {
        if (200 == res.code) {
          const data = res.data.addressComponent;
          queryParam.value.adcode = parseAddressCode(data.adcode);
          queryParam.value.addrAdcode = parseAddressCode(data.adcode)[2];
          queryParam.value.adcodeName = data.district;
          console.log("queryParam.value.adcode", queryParam.value)
          refresh()
        }
      })
      console.log(latitude, longitude)
    },
    fail: function (rr) {
      console.error("getLocation fail", rr)
      Taro.getSetting({
        success: res => {
          if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
            // 用户拒绝了授权
            Taro.showModal({
              title: '提示',
              content: '您拒绝了定位权限，将无法选择地址，修改位置消息',
              success: res => {
                console.log("showModal ", res)
                if (res.confirm) {
                  // 跳转设置页面
                  Taro.openSetting({
                    success: res => {
                      if (res.authSetting['scope.userLocation']) {
                        // 授权成功，重新定位
                        Taro.getLocation({
                          success: res => {

                            console.log("位置信息 ", res)
                          }
                        });
                      } else {
                        // 没有允许定位权限
                        Taro.showToast({
                          title: '您拒绝了定位权限，将无法选择地址，修改位置消息',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
          }
        }
      })
    }
  })
}

const demandData = ref([]);
const idleData = ref([]);
const stockData = ref([]);
const spePriceData = ref([]);

const getDataPage = () => {
  if (queryParam.value.type == "DEMAND") {
    twPublishPageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend",auditStatus:"SUCCESS"}).then(res => {
      if (200 == res.code) {
        demandData.value = [...demandData.value, ...res.data.records]
        queryParam.value.pages = res.data.pages;
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }
  if (queryParam.value.type == "IDLE") {
    twPublishPageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend",auditStatus:"SUCCESS"}).then(res => {
      if (200 == res.code) {
        idleData.value = [...demandData.value, ...res.data.records]
        queryParam.value.pages = res.data.pages;
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }
  if (queryParam.value.type == "STOCK") {
    twProductPageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend",auditStatus:"SUCCESS"}).then(res => {
      if (200 == res.code) {
        stockData.value = [...stockData.value, ...res.data.records]
        queryParam.value.pages = res.data.pages;
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }
  if (queryParam.value.type == "SPE_PRICE") {
    twProductPageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend",auditStatus:"SUCCESS"}).then(res => {
      if (200 == res.code) {
        spePriceData.value = [...spePriceData.value, ...res.data.records]
        queryParam.value.pages = res.data.pages;
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }

}


const refresh = () => {
  queryParam.value.current = 1;
  queryParam.value.size = 10;
  demandData.value = []
  idleData.value = []
  stockData.value = []
  spePriceData.value = []
  getDataPage()
}

const loadMoreLoading = ref(false);
const loadMore = () => {
  if (queryParam.value.current >= queryParam.value.pages) {
    console.log("没有更多数据了")
    Taro.showToast({title: "没有更多数据了", icon: 'none', duration: 1500,});
    return
  }
  loadMoreLoading.value = true
  queryParam.value.current = queryParam.value.current + 1
  getDataPage()
}


const search = () => {
  refresh()
  // console.log("search")
}
const changeTabs = ({title, paneKey, disabled}) => {
  queryParam.value.type = paneKey
  refresh()
}

export default {
  methods: {
    emptyUrl() {
      return emptyUrl
    }
  },

  components: {IconFont},

  // 可以使用所有的 Vue 生命周期方法
  mounted() {
  },

  onLoad() {
    getLocation()

  },

  onReady() {
  },

  onShow() {

  },

  onHide() {
  },

  onPullDownRefresh() {
    console.log("onPullDownRefresh")
    refresh()
  },
  onReachBottom() {
    console.log("onReachBottom")
    loadMore()
  },


  setup() {


    return {
      theme,
      themeVars,
      Taro,
      areaData,
      visible,
      change,

      queryParam,
      search,
      demandData,
      idleData,
      stockData,
      spePriceData,
      changeTabs
    }
  }

}


</script>

<style>
.fixed-bottom {
  position: fixed;
  bottom: 30px;
  left: 0;
  display: flex;
  justify-content: center;
  width: 100%;
}

.city-box {
  font-size: 28px;
  width: 110px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

</style>